#include "Socket.h"
	
	Socket::Socket() {
#ifdef _WIN32
		WSADATA _wsa;
		WSAStartup(0x0202, &_wsa);
		_socket = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
		ip = "127.0.0.1";
#endif
	}

	int Socket::available() {
#ifdef _WIN32
		unsigned long l;
		ioctlsocket(_socket, FIONREAD, &l);
		return (int)l;
#else
		return 0;
#endif
	}

	int Socket::listen(unsigned int port) {
#ifdef _WIN32
		SOCKADDR_IN socket_info;
		socket_info.sin_family = AF_INET;
		socket_info.sin_port = htons(port);
		socket_info.sin_addr.s_addr = inet_addr("127.0.0.1");
		int code = ::bind(_socket, (LPSOCKADDR)&socket_info, sizeof(socket_info));
		if(code == SOCKET_ERROR)
			return code;
		code = ::listen(_socket, SOMAXCONN);
		return code;
#else
#endif
		return 0;
	}

	Socket* Socket::accept() {
#ifdef _WIN32
		sockaddr_in info;
		int len = sizeof(info);
		SOCKET connected = ::accept(_socket, (sockaddr*)&info, &len);
		Socket* _s = new Socket();
		_s->_socket = connected;
		_s->ip = inet_ntoa(info.sin_addr);
		return _s;
#else
#endif
		return nullptr;
	}

	void Socket::close() {
#ifdef _WIN32
		::closesocket(_socket);
#else
#endif
	}

	int Socket::send(char c) {
#ifdef _WIN32
		return ::send(_socket, &c, 1, 0);
#else
#endif
		return 0;
	}

	int Socket::send(unsigned char* src, int size) {
#ifdef _WIN32
		return ::send(_socket, reinterpret_cast<char*>(src), size, 0);
#else
#endif
		return 0;
	}

	int Socket::receive(unsigned char* dest, int size) {
#ifdef _WIN32
		return ::recv(_socket, (char*)dest, size, 0);
#else
#endif
		return 0;
	}